<?php
namespace app\common\model;

use app\common\model\Base;

class Admin extends Base
{
    protected $insert=['create_time'];

    static $disable = [
            0=>'开启',
            1=>'禁用'
        ];

    protected function setCreateTimeAttr(){
        return time();
    }

    public static function disable($key=null){
        if(is_null($key)){
            return self::$disable;
        }else{
            if(isset(self::$disable[$key])){
                return self::$disable[$key];
            }else{
                return false;
            }
        }
    }

    /**
     * 获取分页列表
     * @param  [type] $where    [description]
     * @param  string $queryStr [description]
     * @param  string $baseUrl  [description]
     * @return [type]           [description]
     */
    public function getPageDatas($where,$page,$perpagenum){
        
        $start = ($page-1)*$perpagenum;
                
        $rows = $this
                ->where($where)
                ->limit($start,$perpagenum)
                ->order('id','DESC')->select();

        $count = $this->where($where)->count();
        $data = [];
        if($count){
            foreach($rows as $row):
                $row = $row->toArray();
                $data[] = $this->setField($row);
            endforeach;
        }

        $total_page = ceil($count/$perpagenum);
        return [
            'total_page' => $total_page,
            'curent_page' => $page,
            'count' => $count,
            'data' => $data
        ];
    }

    /**
     * 处理字段数据
     * @param [type] $row [description]
     */
    private function setField($row){
        if(isset($row['create_time'])){
            $row['create_date'] = date("Y-m-d H:i",$row['create_time']);
        }
        if(isset($row['group_id'])){
            $row['group_name'] = AdminGroup::adminGroupData($row['group_id'])['group_name'];
        }
        if(isset($row['disable'])){
            $row['disable_remark'] = self::$disable[$row['disable']];
        }
        return $row;
    }
	
	public function loginCheck($username,$password){
        if(false==($member=$this->isUserExist($username))){
            // 用户不存在
            $this->error='用户不存在';
            return false;
        }
        if(password_verify($password,$member['password'])){
            return $member;
        }else{
            $this->error='密码错误';
            return false;
        }
    }

    public function isUserExist($username){
        if($member = $this->where('username',$username)->whereOr('phone',$username)->find())
            return $member;
        else
            return false;
    }

}